#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件名: send_data.py
功能: 生成测试报告内容，支持邮件和钉钉格式
作者: windows
创建日期: 2025/8/4
版本: 1.1
优化内容:
1. 提取公共函数减少重复代码
2. 增强代码可读性和可维护性
3. 改进报告格式和内容展示
4. 增加类型提示
5. 优化异常处理
"""

from typing import List, Dict, Union


def _calculate_test_results(pass_list: List, fail_list: List, skip_list: List,
                            start_time: str, total_time: float) -> Dict[str, Union[str, int, float]]:
    """计算测试结果并返回结构化数据"""
    pass_num = len(pass_list)
    fail_num = len(fail_list)
    skip_num = len(skip_list)
    count_num = pass_num + fail_num

    # 计算通过率和失败率
    pass_rate = "%.2f%%" % (pass_num / count_num * 100) if count_num > 0 else "0.00%"
    fail_rate = "%.2f%%" % (fail_num / count_num * 100) if count_num > 0 else "0.00%"

    return {
        "test_scenario": "Melynk",
        "team": "测试团队",
        "project": "Melynk",
        "branch": "main",
        "environment": "test环境",
        "tester": "枫叶",
        "run_on": "客户端",
        "execution_time": start_time,
        "total": count_num,
        "passed": pass_num,
        "failed": fail_num,
        "skipped": skip_num,
        "pass_rate": pass_rate,
        "fail_rate": fail_rate,
        "total_time": total_time
    }


def send_email_data(pass_list: List, fail_list: List, skip_list: List,
                    start_time: str, total_time: float) -> str:
    """
    生成邮件格式的HTML测试报告
    :param pass_list: 通过测试用例列表
    :param fail_list: 失败测试用例列表
    :param skip_list: 跳过测试用例列表
    :param start_time: 测试开始时间
    :param total_time: 总耗时(秒)
    :return: HTML格式的报告内容
    """
    test_data = _calculate_test_results(pass_list, fail_list, skip_list, start_time, total_time)
    return _generate_email_html(test_data)


def _generate_email_html(test_data: Dict) -> str:
    """生成邮件HTML内容"""
    return f"""
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>自动化测试报告</title>
    <style>
        body {{ font-family: Arial, sans-serif; line-height: 1.6; }}
        .container {{ max-width: 800px; margin: 0 auto; padding: 20px; }}
        .header {{ color: #333; border-bottom: 2px solid #eee; padding-bottom: 10px; }}
        .section {{ margin-bottom: 20px; }}
        .result-summary {{ background-color: #f9f9f9; padding: 15px; border-radius: 5px; }}
        .passed {{ color: #4CAF50; }}
        .failed {{ color: #F44336; }}
        .skipped {{ color: #FF9800; }}
        .footer {{ margin-top: 20px; font-size: 0.9em; color: #777; }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>自动化测试完成提醒</h1>
        </div>

        <div class="section">
            <h2>测试场景：{test_data.get('test_scenario', 'N/A')}</h2>
            <ul>
                <li><strong>所在团队：</strong>{test_data.get('team', 'N/A')}</li>
                <li><strong>所在项目：</strong>{test_data.get('project', 'N/A')}</li>
                <li><strong>所在分支/版本：</strong>{test_data.get('branch', 'N/A')}</li>
                <li><strong>运行环境：</strong>{test_data.get('environment', 'N/A')}</li>
                <li><strong>测试人：</strong>{test_data.get('tester', 'N/A')}</li>
                <li><strong>运行于：</strong>{test_data.get('run_on', 'N/A')}</li>
                <li><strong>执行时间：</strong>{test_data.get('execution_time', 'N/A')}</li>
            </ul>
        </div>

        <div class="section result-summary">
            <h2>执行结果</h2>
            <ul>
                <li><strong>总数：</strong>{test_data.get('total', 0)}个</li>
                <li class="passed"><strong>通过数：</strong>{test_data.get('passed', 0)}个</li>
                <li class="failed"><strong>失败数：</strong>{test_data.get('failed', 0)}个</li>
                <li class="skipped"><strong>未测数：</strong>{test_data.get('skipped', 0)}个</li>
                <li><strong>通过率：</strong>{test_data.get('pass_rate', '0.00%')}</li>
                <li><strong>失败率：</strong>{test_data.get('fail_rate', '0.00%')}</li>
                <li><strong>总耗时：</strong>{float(test_data.get('total_time', 0)):.3f}秒</li>
            </ul>
        </div>

        <div class="footer">
            <hr>
            <p>此邮件由自动化测试系统生成，请勿直接回复。</p>
        </div>
    </div>
</body>
</html>
"""


def send_dingding_data(pass_list: List, fail_list: List, skip_list: List,
                       start_time: str, total_time: float) -> str:
    """
    生成钉钉格式的Markdown测试报告
    :param pass_list: 通过测试用例列表
    :param fail_list: 失败测试用例列表
    :param skip_list: 跳过测试用例列表
    :param start_time: 测试开始时间
    :param total_time: 总耗时(秒)
    :return: Markdown格式的报告内容
    """
    test_data = _calculate_test_results(pass_list, fail_list, skip_list, start_time, total_time)
    return _generate_dingding_markdown(test_data)


def _generate_dingding_markdown(test_data: Dict) -> str:
    """生成钉钉Markdown内容"""
    # 根据测试结果生成表情符号
    passed_emoji = "✅" if test_data.get('failed', 0) == 0 else "⚠️"

    return f"""
### {passed_emoji} 自动化测试完成提醒 - {test_data.get('test_scenario', 'N/A')}

#### 测试信息
- **团队**: {test_data.get('team', 'N/A')}
- **项目**: {test_data.get('project', 'N/A')}
- **分支**: {test_data.get('branch', 'N/A')}
- **环境**: {test_data.get('environment', 'N/A')}
- **执行人**: {test_data.get('tester', 'N/A')}
- **运行平台**: {test_data.get('run_on', 'N/A')}
- **执行时间**: {test_data.get('execution_time', 'N/A')}

#### 测试结果
- **总数**: {test_data.get('total', 0)} 个
- **通过数**: {test_data.get('passed', 0)} 个
- **失败数**: {test_data.get('failed', 0)} 个
- **跳过数**: {test_data.get('skipped', 0)} 个
- **通过率**: {test_data.get('pass_rate', '0.00%')}
- **失败率**: {test_data.get('fail_rate', '0.00%')}
- **总耗时**: {float(test_data.get('total_time', 0)):.3f} 秒

---

**测试状态**: {"通过" if test_data.get('failed', 0) == 0 else "失败"}
"""